package com.sunnyweather.android.ui.place

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.RecyclerView
import com.sunnyweather.android.R
import com.sunnyweather.android.logic.model.Place
import com.sunnyweather.android.ui.weather.WeatherActivity

class PlaceAdapter(private val fragment: PlaceFragment, private val placeList: List<Place>) :
    RecyclerView.Adapter<PlaceAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaceAdapter.ViewHolder {
        //设置地点列表中每一个地点框的布局
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.place_item, parent, false)

        val holder = ViewHolder(view)
        //设置点击地点后出发的事件
        holder.itemView.setOnClickListener {
            //获取地点信息
            val position = holder.adapterPosition
            val place = placeList[position]

            //获取使用这个adapter的fragment的activity
            val activity = fragment.activity

            //activity如果是WeatherActivity
            if (activity is WeatherActivity) {
                activity.findViewById<DrawerLayout>(R.id.drawerLayout).closeDrawers()
                //更新activity的数据层的数据
                activity.viewModel.locationLng = place.location.lng
                activity.viewModel.locationLat = place.location.lat
                activity.viewModel.placeName = place.name

                activity.refreshWeather()
            } else {
                //不是WeatherActivity，那就是MainActivity了
                //启动WeatherActivity，并传入地址信息
                val intent = Intent(parent.context, WeatherActivity::class.java).apply {
                    putExtra("location_lng", place.location.lng)
                    putExtra("location_lat", place.location.lat)
                    putExtra("place_name", place.name)
                }
                //启动WeatherActivity，关闭MainActivity
                fragment.startActivity(intent)
                activity?.finish()
            }

            //保存此次输入的地址信息，以便下次使用
            fragment.viewModel.savePlace(place)
        }
        return holder
    }

    override fun onBindViewHolder(holder: PlaceAdapter.ViewHolder, position: Int) {
        val place = placeList[position]
        holder.placeAddress.text = place.address
        holder.placeName.text = place.name
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val placeName: TextView = view.findViewById(R.id.placeName)
        val placeAddress: TextView = view.findViewById(R.id.placeAddress)
    }

    override fun getItemCount() = placeList.size
}